package parserdecoder

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"iptv_server/v3/v2_src/utils/common"
	"strings"
)

func NewDecoderTXT() Decoder {
	m := &DecodeTxt{}
	return m
}

type DecodeTxt struct {
}

func (d *DecodeTxt) Decode(w io.Writer, kvs *kkv) (err error) {

	writer := bufio.NewWriter(w)

	channelnameTrans := New_channelnameTrans()
	ipv6Trans := New_name_replaceIPV6()

	countChannels := 0
	for i := 0; i < kvs.Size(); i++ {
		k, v, ok := kvs.GetPair(i)
		if !ok || common.IsEmpty(v) {
			continue
		}

		// group
		writer.WriteString("\n")
		if err != nil {
			return
		}

		_, err = writer.WriteString(ipv6Trans(k, IPV6_STR))
		if err != nil {
			return
		}
		_, err = writer.WriteString(",#genre#")
		if err != nil {
			return
		}
		_, err = writer.WriteString("\n")
		if err != nil {
			return
		}

		// channels
		// for k2, v2s := range v {
		for i2 := 0; i2 < v.Size(); i2++ {
			// k2 == id
			k2, v2s, ok := v.GetPair(i2)
			if !ok {
				continue
			}
			suffix := ""
			channelName := ""
			for count, v2 := range v2s {
				// k2 == id
				if len(channelName) == 0 {
					channelName = v2.name
					if len(channelName) == 0 {
						channelName = k2
					}
					channelName = strings.ReplaceAll(channelName, ",", " ")
					channelName = channelnameTrans(channelName)
					channelName = ipv6Trans(channelName, IPV6_STR)
				}
				// name,url
				_, err = writer.WriteString(channelName)
				if err != nil {
					return
				}
				writer.WriteString(suffix)
				writer.WriteString(",")

				writer.WriteString(v2.url)
				_, err = writer.WriteString("\n")
				if err != nil {
					return
				}

				// 源太多的话-> 10个 1 channel.
				if count%10 == 0 && count > 0 {
					suffix = fmt.Sprintf("  %d", count/10)
				}
				countChannels++
			}
		}

		// flush channels
		err = writer.Flush()

		if err != nil {
			return
		}
	}

	if countChannels == 0 {
		return errors.New("no channel found")
	}
	return nil
}
